import {Button, Form} from "antd";
import React, {FC, useCallback, useMemo} from "react";
import "./css/BaseFormItem.less";
import {useTranslation} from "react-i18next";
import GlobalIcon from "../../global/GlobalIcon.tsx";

interface BaseFormItemProps {
    menuId: string,
    viewItem: any,
    initValue: any,
    hideValid: boolean,
    onRemove: Function
}

const BaseFormItem: FC<BaseFormItemProps> = (props) => {

    const {t} = useTranslation();

    const handleRemove = useCallback((field: string) => {
        props.onRemove && props.onRemove(field);
    }, [props.onRemove]);

    const getFormItemInput = useCallback((viewItem: any) => {
        const {component: InputCom = "Input", field}: { field: string } = viewItem;
        let inputId: string = field;
        if (field.indexOf("name") !== -1) {
            inputId = field.replace(/name/g, "nasme");
        }
        return <InputCom {...viewItem.props}
                         id={inputId}
                         value={viewItem.initValue}
                         ds={viewItem.dataSource}
                         menuId={props.menuId}
                         style={{width: "100%"}}/>
    }, [props.menuId]);

    const renderBaseFormItem = useMemo(() => {
        const {viewItem, dataSource, initValue}:
                { viewItem: any, dataSource: any, initValue: any } = props,
            {field, help, component: InputCom = "Input", required, isSubmit, isShowRemove, rules}:
                {
                    field: string,
                    help: string,
                    component: any,
                    required: boolean,
                    isSubmit: boolean,
                    isShowRemove: boolean
                    rules: any
                } = viewItem;
        const {formatInit} = InputCom;
        let newRules;
        if (required && isSubmit) {
            newRules = [{
                required: true,
                message: t("inputNotNull"),
            }, ...rules]
        } else {
            newRules = rules
        }
        return (
            <div className="sf_core_data_form_item">
                <Form.Item
                    className="sf_core_data_form_item_value"
                    name={field}
                    help={help}
                    initialValue={formatInit ? formatInit(initValue, dataSource, viewItem) : initValue}
                    rules={newRules}
                >
                    {getFormItemInput(viewItem)}
                </Form.Item>
                {isShowRemove && !required ?
                    <div className="sf_core_data_form_item_remove">
                        <Button icon={<GlobalIcon name="icon-close"/>} onClick={() => handleRemove(field)}/>
                    </div> : null}
            </div>
        )
    }, [props]);

    return (renderBaseFormItem);
};

export default React.memo(BaseFormItem);